<template>
  <div id="main">
    <h2>学生管理</h2>
    <div class="head">
      <el-button type="primary" style="margin: 20px" @click="handleOpen('添加孩子', 1)">添加学生信息</el-button>
      <el-input v-model="searchTableInfo" placeholder="请输入搜索内容" style="width:240px;float: right;margin:20px;" />
    </div>
    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="序号" type="index" align="center">
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="studentName"
          label="孩子姓名"
        />

        <el-table-column
          align="center"
          prop="studentId"
          label="学员编号"
        />

        <el-table-column
          align="center"
          prop="studentBirth"
          label="出生日期"
        />

        <el-table-column
          align="center"
          prop="studentJoinCenter"
          label="进入中心日期"
        />

        <el-table-column
          align="center"
          prop="studentPhone"
          label="联系电话"
        />

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <el-button type="primary" icon="el-icon-edit" @click="handleOpen('修改孩子', 2, Scope.row.studentId)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleDelete(Scope.row.studentId, Scope.row.studentName)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- --------------------------------------------------------------------------------------------------------- -->
    <el-dialog title="" :close-on-click-modal="false" :visible.sync="is_add_mother" :before-close="handleClose_m">
      <el-form ref="mother" :model="mother" label-position="top">
        <el-form-item prop="parentName" label="母亲姓名" :label-width="formLabelWidth">
          <el-input v-model="mother.parentName" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentCall" label="母亲电话" :label-width="formLabelWidth">
          <el-input v-model="mother.parentCall" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentEmail" label="母亲邮箱" :label-width="formLabelWidth">
          <el-input v-model="mother.parentEmail" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentAdd" label="家庭住址" :label-width="formLabelWidth">
          <el-input v-model="mother.parentAdd" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentBirthtoString" label="母亲生日" :label-width="formLabelWidth">
          <el-date-picker
            v-model="mother.parentBirthtoString"
            type="date"
            placeholder="选择生日"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item prop="parentEducationalLevel" label="母亲文化水平" :label-width="formLabelWidth">
          <el-input v-model="mother.parentEducationalLevel" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentOccupation" label="母亲职业" :label-width="formLabelWidth">
          <el-input v-model="mother.parentOccupation" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose_m">取 消</el-button>
        <el-button type="primary" @click="handleAddMother('mother')">添 加</el-button>
      </div>
    </el-dialog>
    <!-- -------------------------------------------------------------------------------------------------------- -->
    <el-dialog title="" :close-on-click-modal="false" :visible.sync="is_add_father" :before-close="handleClose_f">
      <el-form ref="father" :model="father" label-position="top">
        <el-form-item prop="parentName" label="父亲姓名" :label-width="formLabelWidth">
          <el-input v-model="father.parentName" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentCall" label="父亲电话" :label-width="formLabelWidth">
          <el-input v-model="father.parentCall" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentEmail" label="父亲邮箱" :label-width="formLabelWidth">
          <el-input v-model="father.parentEmail" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentAdd" label="家庭住址" :label-width="formLabelWidth">
          <el-input v-model="father.parentAdd" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentBirthtoString" label="父亲生日" :label-width="formLabelWidth">
          <el-date-picker
            v-model="father.parentBirthtoString"
            type="date"
            placeholder="选择生日"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item prop="parentEducationalLevel" label="父亲文化水平" :label-width="formLabelWidth">
          <el-input v-model="father.parentEducationalLevel" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="parentOccupation" label="父亲职业" :label-width="formLabelWidth">
          <el-input v-model="father.parentOccupation" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose_f">取 消</el-button>
        <el-button type="primary" @click="handleAddFather('father')">添 加</el-button>
      </div>
    </el-dialog>
    <!-- --------------------------------------------------------------------------------------------------------- -->
    <el-dialog title="" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="handleClose" width="1000px">
      <el-form ref="student" :model="student" label-position="top">
        <el-form-item prop="studentName" label="学生姓名" :label-width="formLabelWidth">
          <el-input v-model="student.studentName" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentSex" label="性别" :label-width="formLabelWidth">
          <el-select v-model="student.studentSex" placeholder="学生性别">
            <el-option key="0" label="女" value="0" />
            <el-option key="1" label="男" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="学生头像">
          <el-upload
            class="avatar-uploader"
            name="files"
            :action="url"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item prop="studentNation" label="学生民族" :label-width="formLabelWidth">
          <el-input v-model="student.studentNation" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentLanguageEnv" label="语言环境" :label-width="formLabelWidth">
          <el-input v-model="student.studentLanguageEnv" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentBirth" label="出生日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="student.studentBirth"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item prop="studentJoinCenter" label="进入中心日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="student.studentJoinCenter"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item prop="studentResidence" label="户口所在地" :label-width="formLabelWidth">
          <el-input v-model="student.studentResidence" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentAddress" label="家庭住址" :label-width="formLabelWidth">
          <el-input v-model="student.studentAddress" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentPhone" label="联系电话" :label-width="formLabelWidth">
          <el-input v-model="student.studentPhone" autocomplete="off" />
        </el-form-item>

        <el-form-item label="父亲姓名" :label-width="formLabelWidth">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item prop="studentFatherId">
              <el-select v-model="student.studentFatherId" filterable placeholder="请选择">
                <el-option
                  v-for="f in father"
                  :key="f.parentId"
                  :label="f.String"
                  :value="f.parentId"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addF(1, 1)">添加</el-button>
            </el-form-item>
          </el-form>
        </el-form-item>

        <el-form-item prop="studentMotherId" label="母亲姓名" :label-width="formLabelWidth">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item prop="studentMotherId">
              <el-select v-model="student.studentMotherId" filterable placeholder="请选择">
                <el-option
                  v-for="f in mother"
                  :key="f.parentId"
                  :label="f.String"
                  :value="f.parentId"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addM(1, 1)">添加</el-button>
            </el-form-item>
          </el-form>
        </el-form-item>

        <el-form-item prop="studentCare" label="主要带养人" :label-width="formLabelWidth">
          <el-input v-model="student.studentCare" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentAccompanyTrainer" label="陪同训练人" :label-width="formLabelWidth">
          <el-input v-model="student.studentAccompanyTrainer" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentBrothers" label="有无兄弟姐妹" :label-width="formLabelWidth">
          <el-select v-model="student.studentBrothers" placeholder="请选择">
            <el-option key="0" label="无" value="0" />
            <el-option key="1" label="有" value="1" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="student.studentBrothers == 1" prop="brothersSituation" label="兄弟姐妹情况" :label-width="formLabelWidth">
          <el-input v-model="student.brothersSituation" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentTreatTime" label="就诊日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="student.studentTreatTime"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item prop="studentTreatHospital" label="就诊医院名称" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatHospital" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentTreatCurrentDiagnosis" label="目前诊断" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatCurrentDiagnosis" autocomplete="off" maxlength="500" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item prop="studentTreatPastTrainingHistoryId" label="既往训练史" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatPastTrainingHistoryId" autocomplete="off" maxlength="500" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item prop="studentTreatTrainingAge" label="起训年龄" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatTrainingAge" autocomplete="off" />
        </el-form-item>

        <el-form-item prop="studentTreatOtherDiseases" label="其他疾病" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatOtherDiseases" autocomplete="off" maxlength="500" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item prop="studentTreatAttention" label="训练注意事项" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatAttention" autocomplete="off" maxlength="500" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item prop="studentTreatClinicInformation" label="临床信息" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatClinicInformation" autocomplete="off" maxlength="500" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item prop="studentTreatAssessmentInformation" label="评估信息" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatAssessmentInformation" autocomplete="off" maxlength="500" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item prop="studentTreatDiagnosisCases" label="诊断病例" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatDiagnosisCases" autocomplete="off" maxlength="500" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item prop="studentTreatTrainingPrescription" label="训练处方" :label-width="formLabelWidth">
          <el-input v-model="student.studentTreatTrainingPrescription" autocomplete="off" maxlength="500" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 20 }" placeholder="请输入内容" />
        </el-form-item>

        <el-form ref="train" label-position="top" :inline="true" :model="train" label-width="100px">

          <el-form-item label="既往训练机构记录" :inline="true" :label-width="formLabelWidth">
            <el-button icon="el-icon-plus" circle size="small" style="margin-left: 20px" @click="addTrains()" />
            <div v-for="(item, index) in train" :key="index">
              <el-form-item label="训练时间" style="margin-right:0px">
                <el-col :span="11">
                  <el-form-item :prop="'train.'+index+'.timeStart'">
                    <el-date-picker v-model="item.timeStart" value-format="yyyy-MM-dd" type="date" style="width: 140px;" />
                  </el-form-item>
                </el-col>
                <el-col :span="11" style="margin-left:5px;">
                  <el-form-item :prop="'train.'+index+'.timeEnd'">
                    <el-date-picker v-model="item.timeEnd" value-format="yyyy-MM-dd" type="date" style="width: 140px;" />
                  </el-form-item>
                </el-col>
              </el-form-item>
              <el-form-item label="机构名称" :prop="'train.'+index+'.orgName'">
                <el-input v-model="item.orgName" clearable style="width:290px;" class="el-in-left-more" />
              </el-form-item>
              <el-form-item label="效果" :prop="'train.'+index+'.effect'" style="margin-left:8px">
                <el-input v-model="item.effect" clearable style="width:285px;" class="el-in-left-more" />
              </el-form-item>
              <el-button style="margin-top:50px" type="danger" icon="el-icon-delete" circle @click="deleteItem(item, index)" />
            </div>
          </el-form-item>
        </el-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button v-if="editType == 2" type="primary" @click="handleUpdate('student')">修 改</el-button>
        <el-button v-if="editType == 1" type="primary" @click="handleAdd('student')">添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { newAdd, deleteChild, newUpdate, getAllChild, getChildById, getAllParent } from '@/api/child'
import { addFather, addMother } from '@/api/parent'
import store from '@/store/index'
export default {
  data() {
    return {
      url: process.env.VUE_APP_BASE_API + 'file/',
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      tableList: [],
      father: [],
      mother: [],
      imageUrl: '',
      searchTableInfo: '',
      listLoading: false,
      dialogFormVisible: false,
      is_add_father: false,
      is_add_mother: false,
      jurisdiction: [],
      editType: 1, // 1 添加 2 修改
      train: [],
      stuId: null,
      student: {},
      formLabelWidth: '200px'
    }
  },
  computed: {
    // 根据计算属性模糊搜索
    list() {
      const searchTableInfo = this.searchTableInfo

      if (searchTableInfo) {
        // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
        // 注意： filter() 不会对空数组进行检测。
        // 注意： filter() 不会改变原始数组。
        return this.tableList.filter(data => {
          // some() 方法用于检测数组中的元素是否满足指定条件;
          // some() 方法会依次执行数组的每个元素：
          // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
          // 如果没有满足条件的元素，则返回false。
          // 注意： some() 不会对空数组进行检测。
          // 注意： some() 不会改变原始数组。
          return Object.keys(data).some(key => {
            // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
            // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
            return (
              String(data[key])
                .toLowerCase()
                .indexOf(searchTableInfo) > -1
            )
          })
        })
      }
      return this.tableList
    }
  },
  created() {
    this.fetchData()
    this.getparent()
  },
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {

    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.obj.split(';')[0]
      this.student.studentHeadImages = this.imageUrl
    },
    beforeAvatarUpload(file) {
      const isImage =
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG或PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isImage && isLt2M
    },
    showSex(row, column) {
      if (row.studentSex === '1') {
        return '男'
      }
      if (row.studentSex === '0') {
        return '女'
      }
    },
    // --------------------------------------------动态增加input框---------------------------------------------
    addTrains() {
      this.train.push({
        staffId: store.getters.userId,
        studentId: this.stuId,
        timeStart: '',
        timeEnd: '',
        orgName: '',
        effect: ''
      })
    },
    deleteItem(item, index) {
      this.train.splice(index, 1)
      // if (this.editType === 2) {
      //   delTrain(item.trainingInstitutionRecordId)
      // }
    },
    // -------------------------------------------------------------------------------------------------------
    getparent: function() {
      getAllParent(1).then(resp => {
        this.father = resp.obj
      })
      getAllParent(0).then(r => {
        this.mother = r.obj
      })
    },

    fetchData() {
      this.listLoading = true
      getAllChild().then(data => {
        this.tableList = data.obj
        this.listLoading = false
      })
      getAllParent(1).then(f => {
        this.father = f.obj
      })
      getAllParent(0).then(m => {
        this.mother = m.obj
      })
    },
    addF(sex, childId) {
      this.is_add_father = true
    },
    addM(sex, childId) {
      this.is_add_mother = true
    },
    handleOpen(title, type, id) {
      this.student = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      this.stuId = id
      if (type === 2) {
        getChildById(id).then(resp => {
          this.student = resp.obj.student

          this.train = resp.obj.TrainingInstitutionRecords
          this.student.studentBrothers = String(this.student.studentBrothers)
          this.student.studentSex = String(this.student.studentSex)
          this.imageUrl = this.student.studentHeadImages
          // this.trainList = resp.obj.TrainingInstitutionRecords
        })
      }
    },
    handleClose() {
      this.student = {}
      this.train = []
      this.imageUrl = ''
      this.stuId = null
      this.dialogFormVisible = false
    },
    handleDelete(id, username) {
      this.$confirm('确认删除该学生？姓名为' + username).then(() =>
        deleteChild(id).then(data => {
          this.$notify({
            title: '操作成功',
            type: 'success'
          })
          const totalPage = Math.ceil((this.list.length - 1) / this.pagesize)
          const page =
            this.currentPage > totalPage ? totalPage : this.currentPage
          this.currentPage = this.currentPage < 1 ? 1 : page
          this.fetchData()
        })
      )
    },
    handleUpdate(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          newUpdate(this.student, this.train).then((resp) => {
            this.$notify({
              title: '修改成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.student = {}
          this.train = []
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleAdd(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          newAdd(this.student, this.train).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            this.fetchData()
          })
          this.student = {}
          this.train = []
          this.dialogFormVisible = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },

    handleAddMother(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addMother(this.mother).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })
            getAllParent(0)
            this.fetchData()
          })
          this.mother = {}
          this.is_add_mother = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleAddFather(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          addFather(this.father).then(resp => {
            this.$notify({
              title: '操作成功',
              type: 'success'
            })

            this.fetchData()
          })
          this.father = {}
          this.is_add_father = false
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleClose_f() {
      this.is_add_father = false
      this.father = {}
    },
    handleClose_m() {
      this.is_add_mother = false
      this.mother = {}
    }
  }
}
</script>

<style scoped>
#main {
  margin-left: 5px;
  margin-right: 5px;
}
#table-area {
  margin-left: 10px;
  margin-right: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}
</style>
